package buffer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;

public class SocketTimePrint {
    private static final Logger logger = Logger.getLogger(String.valueOf(SocketTimePrint.class));

    public static void main(String[] args) throws Exception {
        Thread server = new Thread(new ServerMsgNoselector());
        Thread client = new Thread(new ClientMsg());

        logger.info("Beginning to start the server for message");
        server.start();
        Thread.sleep(100);
        logger.info("Beginning to start the client for message");
        client.start();
    }
}

class ClientMsg implements Runnable {
    private static final Logger logger = Logger.getLogger(String.valueOf(ClientMsg.class));

    public void run() {
        try {
            SocketChannel socket = SocketChannel.open();
            socket.connect(new InetSocketAddress("127.0.0.1", 9999));
            socket.configureBlocking(false);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            while (true) {
                String datestr = format.format(new Date());
                ByteBuffer buff = ByteBuffer.wrap(datestr.getBytes());
                socket.write(buff);
                Thread.sleep(2000);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class ServerMsgNoselector implements Runnable {
    private static final Logger logger = Logger.getLogger(String.valueOf(ServerMsgNoselector.class));

    public void run() {
        try {
            ServerSocketChannel serverChannel = ServerSocketChannel.open();
            ServerSocket socket = serverChannel.socket();
            socket.bind(new InetSocketAddress(9999));
            serverChannel.configureBlocking(true);

            SocketChannel client = serverChannel.accept();
            client.configureBlocking(true);
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (true) {
                int len = client.read(buffer);
                if (len > 0 && buffer.hasArray()) {
                    String msg = new String(buffer.array(), 0, len);
                    logger.info("The recvicing message is " + msg);
                } else {
                    logger.info("Waiting for message ...");
                }
                buffer.clear();
            }
        } catch (Exception ie) {
            ie.printStackTrace();
        }
    }
}
